package the.broccoli.uc.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.wisteria.framework.util.EncryptUtils;
import org.wisteria.framework.web.APIResult;
import org.wisteria.framework.web.BusinessException;
import org.wisteria.framework.web.util.HttpUtils;
import the.broccoli.auth.AuthUtils;
import the.broccoli.auth.SessionUser;
import the.broccoli.auth.UserContext;
import the.broccoli.setting.service.ILogService;
import the.broccoli.uc.constant.AuthErrorCode;
import the.broccoli.uc.controller.req.UserLoginReq;
import the.broccoli.uc.entity.User;
import the.broccoli.uc.service.IUserService;
import the.broccoli.uc.controller.req.WXLoginReq;
import the.broccoli.uc.service.LoginService;
import the.broccoli.uc.service.TokenService;
import the.broccoli.uc.service.dto.TokenDTO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.Map;

/**
 * 登录认证控制器
 */
@RestController
@RequestMapping("/auth")
public class LoginController {

    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private IUserService userService;

    @Autowired
    private ILogService logService;

    @Resource
    private LoginService loginService;

    @Resource
    private TokenService tokenService;

    /**
     * 用户登录PC端
     * @return
     */
    @PostMapping("/user/login")
    public APIResult userLogin(@RequestBody UserLoginReq req) {
        try {
            AuthUtils.login(req.getAccount(), req.getPassword());
        } catch (UnknownAccountException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_IS_NOT_EXIST);
        } catch (ExcessiveAttemptsException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_IS_DISABLED);
        } catch (IncorrectCredentialsException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_PASSWORD_IS_ERROR);
        } catch (Exception e) {
            throw BusinessException.withErrorCode(APIResult.statusCode.fail.name());
        }


        SessionUser sessionUser = UserContext.getSessionUser();
        logService.loginLog(sessionUser.getTenantId()+"", sessionUser.getUserId(), sessionUser.getUserName(), HttpUtils.getIp());
        return APIResult.success(sessionUser);
    }

    @PostMapping("/login")
    public APIResult login(
            @ApiParam(name = "account", value = "账号", required = true, defaultValue = "139")
            @RequestParam(name = "account") String account,
            @ApiParam(name = "password", value = "密码", required = true, defaultValue = "123456")
            @RequestParam(name = "password") String password,
            @RequestParam(name = "remember", required = false) String remember,
            @RequestParam(name = "captcha", required = false) String captcha,
            HttpServletRequest request
    ) {
        String priKey = (String)request.getSession().getAttribute("PRIVATE_KEY");        
        password = EncryptUtils.decrypt(password, priKey);
        LOG.info("==>priKey:"+priKey);
        LOG.info("==>password:"+password);
        try {
            AuthUtils.login(account, password);
        } catch (UnknownAccountException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_IS_NOT_EXIST);
        } catch (ExcessiveAttemptsException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_IS_DISABLED);
        } catch (IncorrectCredentialsException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_PASSWORD_IS_ERROR);
        } catch (Exception e) {
            throw BusinessException.withErrorCode(APIResult.statusCode.fail.name());
        }


        SessionUser sessionUser = UserContext.getSessionUser();
        sessionUser.setToken(AuthUtils.getSessionId());
        logService.loginLog(sessionUser.getTenantId()+"", sessionUser.getUserId(), sessionUser.getUserName(), HttpUtils.getIp());
        return APIResult.success(sessionUser);
    }

    @PostMapping("/check")
    public APIResult check(
            @ApiParam(name = "account", value = "账号", required = true, defaultValue = "139")
            @RequestParam(name = "account") String account,
            @ApiParam(name = "password", value = "密码", required = true, defaultValue = "123456")
            @RequestParam(name = "password") String password,
            @RequestParam(name = "remember", required = false) String remember,
            @RequestParam(name = "captcha", required = false) String captcha,
            HttpServletRequest request
    ) {
        try {
            AuthUtils.login(account, password);
        } catch (UnknownAccountException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_IS_NOT_EXIST);
        } catch (ExcessiveAttemptsException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_IS_DISABLED);
        } catch (IncorrectCredentialsException e) {
            throw BusinessException.withErrorCode(AuthErrorCode.AUTH_ACCOUNT_PASSWORD_IS_ERROR);
        } catch (Exception e) {
            throw BusinessException.withErrorCode(APIResult.statusCode.fail.name());
        }


        SessionUser sessionUser = UserContext.getSessionUser();
        sessionUser.setToken(AuthUtils.getSessionId());
        logService.loginLog(sessionUser.getTenantId()+"", sessionUser.getUserId(), sessionUser.getUserName(), HttpUtils.getIp());
        return APIResult.success(sessionUser);
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public APIResult logout() {
        String userName = UserContext.userName();
        logService.logoutLog(UserContext.tenantId()+"", UserContext.userId(), UserContext.userName(), HttpUtils.getIp());
        AuthUtils.logout();
        return APIResult.success();
    }

    /**
     * 获取用户会话信息PC端
     * @return
     */
    @GetMapping("/session-info")
    public APIResult sessionInfo() {
        return APIResult.success(UserContext.getSessionUser());
    }

    /**
     * 获取用户会话信息移动端
     * @param token
     * @return
     */
    @GetMapping("/get-session-info")
    public APIResult<SessionUser> getSessionInfo(@RequestParam(name = "token") String token) {
        SessionUser sessionUser = null;
        TokenDTO tokenInfo = tokenService.getTokenInfo(Integer.valueOf(token));
        if (tokenInfo != null
                && StringUtils.hasText(tokenInfo.getContent())) {
            sessionUser = JSON.parseObject(tokenInfo.getContent(), SessionUser.class);
        }
        return APIResult.success(sessionUser);
    }

    @GetMapping("/session-info/validate")
    public APIResult<Boolean> validate(@RequestParam(name = "token") String token) {
        User user = userService.getById(token);
        if (user == null
                || user.getLoginExpire() == null
                || user.getLoginExpire().before(new Date())) {
            return APIResult.success(false);
        }
        return APIResult.success(true);
    }

    /**
     * 登录加密
     */
    @GetMapping("/encrypt")
    public APIResult encrypt(HttpServletRequest request) {
        Map<Integer, String> map = EncryptUtils.genKeyPair();
        request.getSession().setAttribute("PRIVATE_KEY", map.get(1));
        LOG.info("==>PUBLIC_KEY:"+map.get(0));
        LOG.info("==>PRIVATE_KEY:"+map.get(1));
        return APIResult.success(map.get(0));
    }

    /**
     * 微信授权登录
     */
    @PostMapping("/wxlogin")
    public APIResult<SessionUser> wxLogin(@RequestBody @Valid WXLoginReq req) {
        return APIResult.success(loginService.wxLogin(req));
    }
}
